<template>
  <div class="inventory-management-container">
    <!-- 页面标题和操作区 -->
    <div class="page-header">
      <div class="page-title">
        <el-icon><Box /></el-icon>
        <span>库存管理</span>
      </div>
      <div class="page-actions">
        <el-button type="primary" class="add-btn" @click="handleAddInventory">
          <el-icon><Plus /></el-icon> 添加库存
        </el-button>
      </div>
    </div>

    <!-- 统计卡片区域 -->
    <div class="stats-cards">
      <el-row :gutter="20">
        <el-col :xs="12" :sm="8" :md="6" :lg="4" v-for="(type, index) in inventoryTypes" :key="index">
          <div class="stat-card" :class="`stat-card-${getTagType(type) || 'default'}`">
            <div class="stat-icon">
              <el-icon v-if="type === '种子'"><Chicken /></el-icon>
              <el-icon v-else-if="type === '肥料'"><Paperclip /></el-icon>
              <el-icon v-else-if="type === '农药'"><Aim /></el-icon>
              <el-icon v-else-if="type === '工具'"><Scissors /></el-icon>
              <el-icon v-else-if="type === '农产品'"><Apple /></el-icon>
              <el-icon v-else><Collection /></el-icon>
            </div>
            <div class="stat-content">
              <div class="stat-title">{{ type }}</div>
              <div class="stat-value">{{ getInventoryCountByType(type) }} 种</div>
            </div>
          </div>
        </el-col>
        
      </el-row>
    </div>

    <!-- 主要内容区域 -->
    <el-row :gutter="20" class="main-content">
      <el-col :xs="24" :sm="24" :md="16" :lg="18">
        <!-- 库存列表 -->
        <el-card v-loading="loading" class="inventory-list-card" shadow="hover">
          <template #header>
            <div class="card-header">
              <div class="card-title">
                <el-icon><List /></el-icon>
                <span>库存清单</span>
              </div>
              <div class="card-actions">
                <el-input
                  v-model="searchQuery"
                  placeholder="搜索名称或类型"
                  clearable
                  class="search-input"
                >
                  <template #prefix>
                    <el-icon><Search /></el-icon>
                  </template>
                </el-input>
              </div>
            </div>
          </template>

          <div class="table-wrapper">
            <el-table 
              :data="pagedInventory" 
              border 
              stripe 
              :row-class-name="tableRowClassName"
              style="width: 100%;"
            >
              <el-table-column label="物品名称" prop="name" min-width="120">
                <template #default="scope">
                  <div class="inventory-name">{{ scope.row.name }}</div>
                </template>
              </el-table-column>
              <el-table-column label="类型" prop="type" min-width="100">
                <template #default="scope">
                  <el-tag :type="getTagType(scope.row.type)" effect="light">
                    {{ scope.row.type }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column label="数量" prop="quantity" width="120">
                <template #default="scope">
                  <div class="quantity-display" :class="{ 
                    'low-quantity': scope.row.quantity <= (scope.row.alertThreshold || 10) 
                  }">
                    {{ scope.row.quantity }} <span class="unit">{{ scope.row.unit }}</span>
                  </div>
                </template>
              </el-table-column>
              <el-table-column label="入库日期" min-width="120">
                <template #default="scope">
                  <div class="date-display">{{ formatDate(scope.row.date) }}</div>
                </template>
              </el-table-column>
              <el-table-column label="操作" width="150" fixed="right">
                <template #default="scope">
                  <div class="table-actions">
                    <el-button 
                      type="primary" 
                      link 
                      size="small" 
                      @click="handleEdit(scope.row)"
                    >
                      <el-icon><EditPen /></el-icon> 编辑
                    </el-button>
                    <el-button 
                      type="danger" 
                      link 
                      size="small" 
                      @click="handleDelete(scope.row)"
                    >
                      <el-icon><Delete /></el-icon> 删除
                    </el-button>
                  </div>
                </template>
              </el-table-column>
            </el-table>
          </div>

          <div class="pagination-container">
            <el-pagination
              background
              layout="prev, pager, next, jumper, total"
              :total="filteredInventory.length"
              :page-size="pageSize"
              :current-page="currentPage"
              @current-change="handlePageChange"
            />
          </div>
        </el-card>
      </el-col>

      <el-col :xs="24" :sm="24" :md="8" :lg="6">
        <div class="side-cards">
          <!-- 库存分布图表 -->
          <el-card shadow="hover" class="chart-card" v-if="inventory.length > 0">
            <template #header>
              <div class="card-header">
                <div class="card-title">
                  <el-icon><PieChart /></el-icon>
                  <span>库存分布</span>
                </div>
              </div>
            </template>
            
            <div class="chart-container">
              <div 
                v-for="(value, type) in inventoryTypeStats" 
                :key="type"
                class="chart-bar"
              >
                <div class="chart-label">{{ type }}</div>
                <div class="chart-value-container">
                  <div 
                    class="chart-value-bar" 
                    :style="{ 
                      width: `${(value / inventory.length) * 100}%`,
                      backgroundColor: getChartColor(type)
                    }"
                  ></div>
                </div>
                <div class="chart-value">{{ value }}</div>
              </div>
            </div>
          </el-card>
          
          <!-- 库存预警 -->
          <el-card shadow="hover" class="alert-card">
            <template #header>
              <div class="card-header">
                <div class="card-title">
                  <el-icon><WarningFilled /></el-icon>
                  <span>库存预警</span>
                </div>
              </div>
            </template>
            
            <div v-if="lowInventory.length === 0" class="empty-data">
              <el-empty description="暂无库存预警" :image-size="80" />
            </div>
            
            <div v-else class="inventory-alerts">
              <div v-for="item in lowInventory" :key="item.id" class="alert-item">
                <el-alert
                  :title="`${item.name}库存不足`"
                  :description="`当前: ${item.quantity}${item.unit}，低于预警值(${item.alertThreshold || 10}${item.unit})`"
                  type="warning"
                  :closable="false"
                  show-icon
                  class="custom-alert"
                />
              </div>
            </div>
          </el-card>
        </div>
      </el-col>
    </el-row>

    <!-- 添加/编辑库存对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="isEdit ? '编辑库存' : '添加库存'"
      width="500px"
      destroy-on-close
      class="inventory-dialog"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="80px"
        label-position="right"
      >
        <el-form-item label="名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入物品名称" />
        </el-form-item>
        
        <el-form-item label="类型" prop="type">
          <el-select v-model="form.type" placeholder="请选择类型" style="width: 100%">
            <el-option 
              v-for="item in inventoryTypes" 
              :key="item" 
              :label="item" 
              :value="item"
            >
              <span>{{ item }}</span>
              <el-tag size="small" :type="getTagType(item)" style="margin-left: 8px;">
                {{ item }}
              </el-tag>
            </el-option>
          </el-select>
        </el-form-item>
        
        <el-form-item label="数量" prop="quantity">
          <el-input-number
            v-model="form.quantity"
            :min="0"
            :precision="2"
            style="width: 100%"
          />
        </el-form-item>
        
        <el-form-item label="单位" prop="unit">
          <el-input v-model="form.unit" placeholder="请输入单位" />
        </el-form-item>
        
        <el-form-item label="入库日期" prop="date">
          <el-date-picker
            v-model="form.date"
            type="date"
            placeholder="选择日期"
            style="width: 100%"
          />
        </el-form-item>
        
        <el-form-item label="预警值" prop="alertThreshold">
          <el-input-number
            v-model="form.alertThreshold"
            :min="0"
            :precision="2"
            style="width: 100%"
          />
        </el-form-item>
        
        <el-form-item label="备注" prop="note">
          <el-input
            v-model="form.note"
            type="textarea"
            :rows="3"
            placeholder="请输入备注信息"
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm" :loading="submitLoading">
            {{ isEdit ? '更新' : '添加' }}
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 删除确认对话框 -->
    <el-dialog
      v-model="deleteDialogVisible"
      title="删除确认"
      width="400px"
      class="delete-dialog"
    >
      <div class="delete-confirm-content">
        <el-icon class="delete-icon"><WarningFilled /></el-icon>
        <span>确定要删除该库存记录吗？此操作不可撤销。</span>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="deleteDialogVisible = false">取消</el-button>
          <el-button
            type="danger"
            @click="confirmDelete"
            :loading="deleteLoading"
          >
            确定删除
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, reactive, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { 
  Box, Plus, Search, Delete, Edit as EditPen, Warning as WarningFilled, 
  PieChart, List, DataAnalysis, Cherry as Chicken, Paperclip, Aim, 
  ScaleToOriginal as Scissors, Apple, Collection 
} from '@element-plus/icons-vue';
import { useFarmerStore } from '../../store';
import { format } from 'date-fns';

// 获取状态管理
const farmerStore = useFarmerStore();

// 表格数据和分页
const loading = ref(false);
const currentPage = ref(1);
const pageSize = ref(10);
const searchQuery = ref('');
const inventory = ref([]);

// 对话框控制
const dialogVisible = ref(false);
const deleteDialogVisible = ref(false);
const submitLoading = ref(false);
const deleteLoading = ref(false);
const isEdit = ref(false);
const formRef = ref(null);
const currentInventoryId = ref(null);

// 库存类型
const inventoryTypes = [
  '种子',
  '肥料',
  '农药',
  '工具',
  '农产品',
  '其他'
];

// 表单数据
const form = reactive({
  name: '',
  type: '',
  quantity: 0,
  unit: '',
  date: new Date(),
  alertThreshold: 10,
  note: ''
});

// 表单验证规则
const rules = {
  name: [
    { required: true, message: '请输入物品名称', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  type: [
    { required: true, message: '请选择物品类型', trigger: 'change' }
  ],
  quantity: [
    { required: true, message: '请输入数量', trigger: 'blur' },
    { type: 'number', min: 0, message: '数量必须大于等于0', trigger: 'blur' }
  ],
  unit: [
    { required: true, message: '请输入单位', trigger: 'blur' }
  ],
  date: [
    { required: true, message: '请选择入库日期', trigger: 'change' }
  ]
};

// 格式化日期
const formatDate = (date) => {
  if (!date) return '';
  return format(new Date(date), 'yyyy-MM-dd');
};

// 过滤后的库存列表
const filteredInventory = computed(() => {
  if (!searchQuery.value) {
    return inventory.value;
  }
  
  const query = searchQuery.value.toLowerCase();
  return inventory.value.filter(item => {
    return item.name.toLowerCase().includes(query) || 
           item.type.toLowerCase().includes(query);
  });
});

// 分页后的库存列表
const pagedInventory = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value;
  const end = start + pageSize.value;
  return filteredInventory.value.slice(start, end);
});

// 库存预警（数量低于预警值的物品）
const lowInventory = computed(() => {
  return inventory.value.filter(item => {
    return item.quantity <= (item.alertThreshold || 10);
  });
});

// 按类型统计库存
const inventoryTypeStats = computed(() => {
  const stats = {};
  inventory.value.forEach(item => {
    if (!stats[item.type]) {
      stats[item.type] = 0;
    }
    stats[item.type]++;
  });
  return stats;
});

// 获取标签类型
const getTagType = (type) => {
  const typeMap = {
    '种子': 'success',
    '肥料': 'warning',
    '农药': 'danger',
    '工具': 'primary',
    '农产品': 'info'
  };
  return typeMap[type] || '';
};

// 获取图表颜色
const getChartColor = (type) => {
  const colorMap = {
    '种子': '#67C23A',    // 绿色
    '肥料': '#E6A23C',    // 黄色
    '农药': '#F56C6C',    // 红色
    '工具': '#409EFF',    // 蓝色
    '农产品': '#909399',  // 灰色
    '其他': '#8E71C7'     // 紫色
  };
  return colorMap[type] || '#909399';
};

// 设置表格行样式
const tableRowClassName = ({ row }) => {
  if (row.quantity <= (row.alertThreshold || 10)) {
    return 'low-quantity-row';
  }
  return '';
};

// 按类型获取库存数量
const getInventoryCountByType = (type) => {
  return inventory.value.filter(item => item.type === type).length;
};

// 处理添加库存
const handleAddInventory = () => {
  isEdit.value = false;
  resetForm();
  dialogVisible.value = true;
};

// 处理调整库存
const handleEdit = (row) => {
  isEdit.value = true;
  // 始终使用id字段，因为后端期望用id操作
  currentInventoryId.value = row.id;
  console.log('编辑库存项', row);
  console.log('使用ID:', currentInventoryId.value);
  
  Object.assign(form, {
    name: row.name,
    type: row.type,
    quantity: row.quantity,
    unit: row.unit,
    date: new Date(row.date),
    alertThreshold: row.alertThreshold || 10,
    note: row.note || ''
  });
  dialogVisible.value = true;
};

// 处理删除库存
const handleDelete = (row) => {
  // 始终使用id字段，因为后端期望用id操作
  currentInventoryId.value = row.id;
  console.log('删除库存项', row);
  console.log('使用ID:', currentInventoryId.value);
  deleteDialogVisible.value = true;
};

// 确认删除
const confirmDelete = async () => {
  if (!currentInventoryId.value) return;
  
  try {
    deleteLoading.value = true;
    await farmerStore.deleteInventory(currentInventoryId.value);
    ElMessage.success('库存记录删除成功');
    fetchInventory();
    deleteDialogVisible.value = false;
  } catch (error) {
    console.error('删除失败', error);
    ElMessage.error('删除失败: ' + (error.message || '未知错误'));
  } finally {
    deleteLoading.value = false;
  }
};

// 提交表单
const submitForm = async () => {
  if (!formRef.value) return;
  
  await formRef.value.validate(async (valid) => {
    if (!valid) return;
    
    try {
      submitLoading.value = true;
      console.log('提交表单，是否编辑模式:', isEdit.value);
      console.log('当前编辑的库存ID:', currentInventoryId.value);
      
      // 准备提交数据
      const submitData = {
        name: form.name,
        type: form.type,
        quantity: form.quantity,
        unit: form.unit,
        date: form.date,
        alertThreshold: form.alertThreshold,
        note: form.note
      };
      
      if (isEdit.value && currentInventoryId.value) {
        // 更新记录
        console.log('更新库存数据:', submitData);
        await farmerStore.updateInventory(currentInventoryId.value, submitData);
        ElMessage.success('库存记录更新成功');
      } else {
        // 添加记录
        await farmerStore.addInventory(submitData);
        ElMessage.success('库存记录添加成功');
      }
      
      dialogVisible.value = false;
      fetchInventory();
    } catch (error) {
      console.error('提交失败', error);
      ElMessage.error('提交失败: ' + (error.message || '未知错误'));
    } finally {
      submitLoading.value = false;
    }
  });
};

// 重置表单
const resetForm = () => {
  if (formRef.value) {
    formRef.value.resetFields();
  }
  Object.assign(form, {
    name: '',
    type: '',
    quantity: 0,
    unit: '',
    date: new Date(),
    alertThreshold: 10,
    note: ''
  });
};

// 分页处理
const handlePageChange = (val) => {
  currentPage.value = val;
};

// 获取库存数据
const fetchInventory = async () => {
  loading.value = true;
  try {
    const inventoryData = await farmerStore.fetchInventory();
    inventory.value = inventoryData;
  } catch (error) {
    console.error('获取库存失败', error);
    ElMessage.error('获取库存数据失败');
  } finally {
    loading.value = false;
  }
};

// 组件挂载时加载数据
onMounted(() => {
  fetchInventory();
});
</script>

<style scoped>
.inventory-management-container {
  padding: 24px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 60px);
}

/* 页面标题样式 */
.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  padding: 0 8px;
}

.page-title {
  font-size: 24px;
  font-weight: 600;
  color: #303133;
  display: flex;
  align-items: center;
}

.page-title .el-icon {
  margin-right: 12px;
  font-size: 24px;
  color: #409EFF;
}

.add-btn {
  font-weight: 500;
  border-radius: 4px;
  padding: 10px 20px;
  transition: all 0.3s;
}

/* 统计卡片样式 */
.stats-cards {
  margin-bottom: 24px;
}

.stat-card {
  display: flex;
  align-items: center;
  padding: 16px;
  border-radius: 8px;
  background-color: white;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
  margin-bottom: 16px;
  transition: all 0.3s;
}

.stat-card:hover {
  transform: translateY(-3px);
  box-shadow: 0 4px 16px 0 rgba(0, 0, 0, 0.1);
}

.stat-icon {
  font-size: 24px;
  margin-right: 16px;
  width: 42px;
  height: 42px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
}

.stat-content {
  flex: 1;
}

.stat-title {
  font-size: 14px;
  color: #606266;
  margin-bottom: 4px;
}

.stat-value {
  font-size: 20px;
  font-weight: 600;
  color: #303133;
}

/* 不同类型的统计卡片样式 */
.stat-card-success .stat-icon {
  background-color: #67C23A;
}

.stat-card-warning .stat-icon {
  background-color: #E6A23C;
}

.stat-card-danger .stat-icon {
  background-color: #F56C6C;
}

.stat-card-primary .stat-icon {
  background-color: #409EFF;
}

.stat-card-info .stat-icon {
  background-color: #909399;
}

.stat-card-default .stat-icon {
  background-color: #8E71C7;
}

/* 主要内容区域 */
.main-content {
  margin-bottom: 24px;
}

.inventory-list-card {
  margin-bottom: 24px;
  border-radius: 8px;
  overflow: hidden;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-title {
  font-weight: 600;
  display: flex;
  align-items: center;
  font-size: 16px;
  color: #303133;
}

.card-title .el-icon {
  margin-right: 8px;
  font-size: 18px;
}

.table-wrapper {
  margin-bottom: 16px;
}

/* 表格样式定制 */
.inventory-name {
  font-weight: 500;
}

.quantity-display {
  font-weight: 500;
}

.quantity-display.low-quantity {
  color: #F56C6C;
  font-weight: 600;
}

.unit {
  font-size: 12px;
  color: #909399;
  margin-left: 4px;
}

.date-display {
  color: #606266;
}

.table-actions {
  display: flex;
  justify-content: flex-start;
  gap: 8px;
}

/* 设置低库存行的样式 */
:deep(.low-quantity-row) {
  background-color: rgba(245, 108, 108, 0.05);
}

/* 图表卡片样式 */
.side-cards {
  display: flex;
  flex-direction: column;
  gap: 24px;
}

.chart-card, .alert-card {
  border-radius: 8px;
  overflow: hidden;
}

.chart-container {
  padding: 8px 0;
}

.chart-bar {
  display: flex;
  align-items: center;
  margin-bottom: 12px;
}

.chart-label {
  width: 70px;
  font-size: 14px;
  color: #606266;
}

.chart-value-container {
  flex: 1;
  height: 24px;
  background-color: #f5f7fa;
  border-radius: 12px;
  margin: 0 12px;
  overflow: hidden;
}

.chart-value-bar {
  height: 100%;
  min-width: 24px;
  border-radius: 12px;
  transition: width 0.5s ease;
}

.chart-value {
  width: 30px;
  text-align: right;
  font-size: 14px;
  font-weight: 600;
  color: #303133;
}

/* 库存预警样式 */
.inventory-alerts {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.custom-alert {
  border-radius: 4px;
}

/* 删除对话框 */
.delete-confirm-content {
  display: flex;
  align-items: center;
  padding: 16px 0;
}

.delete-icon {
  font-size: 24px;
  color: #F56C6C;
  margin-right: 12px;
}

/* 响应式设计 */
@media (max-width: 992px) {
  .stats-cards {
    overflow-x: auto;
    padding-bottom: 8px;
  }
}

@media (max-width: 768px) {
  .inventory-management-container {
    padding: 16px;
  }
  
  .page-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 16px;
    margin-bottom: 16px;
  }
  
  .search-input {
    width: 100%;
  }
  
  .chart-label {
    width: 60px;
  }
}

@media (max-width: 576px) {
  .stat-card {
    padding: 12px;
  }
  
  .stat-icon {
    width: 36px;
    height: 36px;
    font-size: 18px;
  }
  
  .stat-value {
    font-size: 16px;
  }
}
</style> 